﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using PagedList;
using SIG.Service;
using System;
using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.ViewModel;
using SIG.Infrastructure.Extensions;
using System.Xml.Linq;
using SIG.Infrastructure.Helper;
using SIG.Resources.Admin;
using SIG.ViewModel.Admin.Blogs;
using SIG.InputModel.Admin.Blogs;
using SIG.Service.Blogs;
using SIG.DAL.Dapper.Repositories;
using SIG.DAL.Dapper.Model;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class PostController : BaseController
    {
        private readonly PostCategoryRepository _categoryService;
        private readonly PostRepository _postService;
        private readonly PageMetaRepository _pageMetaService;
        private readonly IMapper _mapper;

        public PostController(IMapper mapper)
        {
            _categoryService = new PostCategoryRepository();
            _postService = new PostRepository();
            _pageMetaService = new PageMetaRepository();
            _mapper = mapper;
            
        }
        #region Posts


        [HttpGet]
        public ActionResult Index(int? page, int? categoryId, string Keyword)
        {

            var postListVM = new PostListVM();

            postListVM.CategoryId = categoryId ?? 0;
            postListVM.PageIndex = (page ?? 1) ;
            postListVM.PageSize = SettingsManager.Blog.PageSize;
            postListVM.Keyword = Keyword;

            int count;
            var posts = _postService.GetListPagedItems(postListVM.PageIndex, postListVM.PageSize, postListVM.CategoryId.Value, postListVM.Keyword, out count);

          //  var postDtos = _mapper.Map<IEnumerable<Post>, IEnumerable<PostVM>>(posts.AsEnumerable());
            //   postListVM.Posts = postDtos;
            postListVM.TotalCount = count;

            var categoryList = _categoryService.GetItems().OrderByDescending(c => c.Importance).ToList();
            foreach(var item in posts)
            {
                item.PostCategory = categoryList.FirstOrDefault(m => m.Id == item.CategoryId);
            }

            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            postListVM.Posts = new StaticPagedList<Post>(posts, postListVM.PageIndex , postListVM.PageSize, postListVM.TotalCount);
            //  ViewBag.OnePageOfPosts = postsAsIPagedList;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(postListVM);

        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/BlogSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        public ActionResult Add()
        {
            var post = new PostIM { Active = true };

            var categorys = _categoryService.GetItems().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;
            return View(post);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Add(PostIM post)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {

                var newPost = _mapper.Map<PostIM, Post>(post);
                newPost.CreatedBy = Site.CurrentUserName;
                newPost.CreatedDate = DateTime.Now;
                _postService.Create(newPost);

                if (!string.IsNullOrEmpty(post.Keywords) || !string.IsNullOrEmpty(post.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newPost.Id.ToString(),
                        Keyword = post.Keywords,
                        Description = post.SEODescription,
                        ModelType = (short)ModelType.BLOG
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }

        [HttpGet]
        public ActionResult Edit(int Id)
        {
            var vPost = _postService.GetById(Id);
            if (vPost == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }


            var editPost = _mapper.Map<Post, PostIM>(vPost);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.BLOG, editPost.Id.ToString());
            if (pageMeta != null)
            {
                editPost.Keywords = pageMeta.Keyword;
                editPost.SEODescription = pageMeta.Description;
            }

            var categorys = _categoryService.GetItems().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;

            return View(editPost);


        }

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public JsonResult Edit(PostIM post)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var editPost = _postService.GetById(post.Id);
                editPost.Summary = post.Summary;
                editPost.Body = post.Body;
                editPost.Active = post.Active;
                editPost.Thumbnail = post.Thumbnail;
                editPost.Title = post.Title;
                editPost.Recommend = post.Recommend;
                editPost.UpdatedBy = Site.CurrentUserName;
                editPost.UpdatedDate = DateTime.Now;

               // var editPost = _mapper.Map<PostIM, Post>(post);
                _postService.Update(editPost);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.BLOG, editPost.Id.ToString());
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(post.Keywords) || !string.IsNullOrEmpty(post.SEODescription))
                {

                    pageMeta.ObjectId = post.Id.ToString();
                    pageMeta.Keyword = post.Keywords;
                    pageMeta.Description = post.SEODescription;
                    pageMeta.ModelType = (short)ModelType.BLOG;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Active(int id)
        {

            Post vPost = _postService.GetById(id);

            try
            {
                vPost.Active = !vPost.Active;
                _postService.Update(vPost);

                var vm = _mapper.Map<PostVM>(vPost);

                AR.Data = RenderPartialViewToString("_PostItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Recommend(int id)
        {

            Post vPost = _postService.GetById(id);

            try
            {
                vPost.Recommend = !vPost.Recommend;
                _postService.Update(vPost);

                var vm = _mapper.Map<PostVM>(vPost);
                AR.Data = RenderPartialViewToString("_PostItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Post vPost = _postService.GetById(id);

            if (vPost == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _postService.Delete(vPost);

            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Post));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        #endregion


    }
}
